package com.example;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CodeGenerator {
    //package 的 包名称
    private static final String BASE_PACKAGE = "com.umsin.cloud"; // 新增基础包名配置
    // 新增输出目录配置
    private static final String OUTPUT_DIR = "E:\\cursor\\test"; // 可以根据需要修改


    private static final String TEMPLATE_PATH = "src/main/resources/templates";
    private static final String JAVA_PATH = "src/main/java/";
    private static final String RESOURCE_PATH = "src/main/resources/";



    public static void main(String[] args) {
        String dbUrl = "jdbc:mysql://ip:3306/dbName";
        String dbUser = "root";
        String dbPassword = "password";
        String author = "Solming";
        List<String> tableNames = Arrays.asList("device_list");
        try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword)) {
            for (String tableName : tableNames) {
                String ddl = getDDL(conn, tableName);
                TableInfo tableInfo = DDLParser.parse(ddl);
                generateCode(tableInfo, author);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getDDL(Connection conn, String tableName) throws Exception {
        String query = "SHOW CREATE TABLE " + tableName;
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(query)) {
            if (rs.next()) {
                return rs.getString(2);
            }
        }
        throw new Exception("无法获取表 " + tableName + " 的DDL");
    }

    private static void generateCode(TableInfo tableInfo, String author) throws Exception {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
        cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));

        generateFile(cfg, "Entity.ftl", tableInfo, author, "Entity", BASE_PACKAGE + ".model.po");
        generateFile(cfg, "DTO.ftl", tableInfo, author, "DTO", BASE_PACKAGE + ".model.dto");
        generateFile(cfg, "Param.ftl", tableInfo, author, "Param", BASE_PACKAGE + ".model.param");
        generateFile(cfg, "Dao.ftl", tableInfo, author, "Mapper", BASE_PACKAGE + ".dao.mapper");
        generateFile(cfg, "Service.ftl", tableInfo, author, "Service", BASE_PACKAGE + ".service");
        generateFile(cfg, "ServiceImpl.ftl", tableInfo, author, "ServiceImpl", BASE_PACKAGE + ".service.impl");
        generateFile(cfg, "Controller.ftl", tableInfo, author, "Controller", BASE_PACKAGE + ".controller.web");
        generateMapperXml(cfg, tableInfo, author);
    }

    private static void generateFile(Configuration cfg, String templateName, TableInfo tableInfo, String author, String suffix, String packageName) throws Exception {
        Template template = cfg.getTemplate(templateName);
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("tableInfo", tableInfo);
        dataModel.put("author", author);
        dataModel.put("packageName", packageName);
        dataModel.put("BASE_PACKAGE", BASE_PACKAGE);

        String fileName = tableInfo.getClassName().substring(0, 1).toUpperCase() + tableInfo.getClassName().substring(1) + suffix + ".java";
        String packagePath = packageName.replace('.', File.separatorChar);
        File outputFile = new File(OUTPUT_DIR + File.separator + JAVA_PATH + File.separator + packagePath, fileName);
        outputFile.getParentFile().mkdirs();

        try (FileWriter out = new FileWriter(outputFile)) {
            template.process(dataModel, out);
        }
    }

    private static void generateMapperXml(Configuration cfg, TableInfo tableInfo, String author) throws Exception {
        Template template = cfg.getTemplate("Mapper.ftl");
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("tableInfo", tableInfo);
        dataModel.put("author", author);
        dataModel.put("BASE_PACKAGE", BASE_PACKAGE);

        String fileName = tableInfo.getClassName() + "Mapper.xml";
        File outputFile = new File(OUTPUT_DIR + File.separator + RESOURCE_PATH  + File.separator + "mappers", fileName);
        outputFile.getParentFile().mkdirs();

        try (FileWriter out = new FileWriter(outputFile)) {
            template.process(dataModel, out);
        }
    }


}

